rm(list = ls())

wd <- ".../Replication/"
setwd(wd)

# Load/install packages --
if (!require("pacman")) install.packages("pacman")
pacman::p_load(
  foreign, 
  ggplot2, 
  estimatr,
  texreg,
  xtable,
  fastDummies,
  sandwich,
  dplyr,
  janitor, 
  gridExtra,
  gsheet,
  zoo,
  interflex,
  lubridate,
  tidyverse,
  stringi,
  readxl,
  ri2,
  modelsummary,
  ggpubr
)

options(scipen=999)

# Note: given the random component inherent to the randomization tests performed
# by ri(), you may observe small differences in the p-values of the randomization
# tests performed using that function.

# load data
lottery <- read.csv("Data/baseline database.csv")
data <- subset(lottery, lottery$group!="Liberado por eleccion")

# Appendix F --------------------------------------------------------------------
#Results Iteratively Excluding Observations

# Exclude one person at a time
coef_loo = c()
p_loo = c()

for(i in 1:nrow(data)){
  
  d.temp = data[-i, ] 
  declare.temp <- declare_ra(N = nrow(d.temp), m=sum(d.temp$lottery_winner)) 
  
  ri_excluding <- summary(conduct_ri(formula = imprisoned_dummy ~ lottery_winner,
                                     declaration = declare.temp, sharp_hypothesis = 0, 
                                     assignment = "lottery_winner",
                                     data = d.temp, sims = 1000))
  
  coef_loo[i] = ri_excluding[2]
  p_loo[i] = ri_excluding[3]
  
  print(i)
  
}

pdf("Output/FigureA7.pdf",height=5, width=10)
par(mfrow=c(1,2))
hist(unlist(coef_loo),
     main = "Leave-one-out coefficients",
     xlab = "Estimated coefficient",
     xlim = c(0,.15),
     breaks = 10)
hist(unlist(p_loo),
     main = "Leave-one-out exact p-values",
     xlab = "Exact p-value",
     xlim = c(0,.15),
     breaks = 10)
dev.off()





